use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn filter_smart(str: String, list: Vec<String>) -> Vec<String> {
    let list = list.iter().map(|v| v.as_str()).collect::<Vec<_>>();
    let result = smart_filter(&str, &list);
    result.into_iter().map(|v| v.to_string()).collect()
}

fn smart_filter<'a>(str: &str, list: &[&'a str]) -> Vec<&'a str> {
    list.iter()
        .filter(|s| is_part_of(str, s))
        .cloned()
        .collect()
}

fn is_part_of(short: &str, long: &str) -> bool {
    let mut start = 0;
    let end = long.len();
    for c in short.chars() {
        let n = end - start;
        let str = long.chars().skip(start).take(n).position(|v| v == c);
        if let Some(i) = str {
            start = i;
        } else {
            return false;
        }
    }
    true
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test() {
        let str = "23";
        let list = vec!["123", "234", "1234", "213", "321"];
        let result = smart_filter(str, &list);
        let actual = vec!["123", "234", "1234", "213"];
        assert_eq!(actual, result);
    }
    #[test]
    fn test1() {
        let str = "北市";
        let list = vec!["北京市", "北平市", "天津市", "北京市政府"];
        let actual = vec!["北京市", "北平市", "北京市政府"];
        let result = smart_filter(str, &list);
        assert_eq!(result, actual);
    }
}
